
const express = require('express');
//引入连接池模块
const pool = require('../pool.js');
//创建路由器对象
const router = express.Router();
//配置multer中间件
//配置multer中间件
const multer = require('multer')
obj = multer.diskStorage({
  destination: function (req, file, cb) { //指定目录
    cb(null, 'upload')
  },
  filename: function (req, file, cb) { // 指定文件名
    // console.log(uuid.v1())
    // console.log(uuid.v4())
    let name = file.originalname
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf('.'))
    cb(null, uuid.v4() + ext)
  }
})
const uploadTools = multer({
  storage: obj
})
const uuid = require('uuid')
//文件上传
//接收文件上传请求
//接收文件上传请求
router.post('/upload',
  uploadTools.array('uploadFile'), (req, res) => {
    console.log(req.files)
    res.send({
      code: "200",
      msg: "ok",
      path: req.files[0].path
    })
  })
//文件上传结束
// products
// 获取所有的商品一级分类
router.get('/firstcategory', (req, res) => {
  let sql = 'SELECT id,name FROM first_type_table ORDER BY id';
  // 执行SQL查询
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ code: 200, message: '查询成功', results: results });
  });
});

// 获取所有的商品二级分类
router.get('/secondcategory', (req, res) => {
  var sid = req.query.sid;
  let sql = 'SELECT * FROM second_type_table where first_type_id=?  ORDER BY id';
  // 执行SQL查询
  pool.query(sql, [sid], (error, results) => {
    if (error) throw error;
    res.send({ code: 200, message: '查询成功', results: results });
  });
});
// 获取所有一级类目下的商品
router.get("/firstcategorypro", (req, res) => {
  var obj = req.query;
  var sql =' SELECT * FROM good_table where first_type_id = ?';
  pool.query(sql, [obj.first_type_id], (err, result) => {
    if (err)
      console.log(err);
    res.send(result);
  })//访问http://localhost:3000/index.html
})  //会看到花括号！
// 获取所有二级类目下的商品
router.get("/secondcategorypro", (req, res) => {
  var obj = req.query;
  var sql =' SELECT * FROM good_table where second_type_id = ?';
  pool.query(sql, [obj.second_type_id], (err, result) => {
    if (err)
      console.log(err);
    res.send(result);
  })//访问http://localhost:3000/index.html
})  //会看到花括号！
// 添加二级类目
router.get('/addsecondt', (req, res) => {
  //1.1获取gett请求的数据
  var obj = req.query;
  console.log(obj);
  //1.2验证各项数据是否为空
  var i = 400;
  for (var k in obj) {
    i++;
    if (!obj[k]) {
      res.send({ code: i, msg: k + '不能为空' });
      return;
    }
  }
  //1.3执行SQL命令，将数据插入到数据表
  pool.query('insert into second_type_table set ?', [obj], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    res.send({ code: 200, msg: '添加成功' });
  });
});
// 模糊查询
router.get("/", (req, res) => {
  var kw = req.query.kw;
  var kws = kw.split(" ");
  kws.forEach((elem, i, kws) =>
    kws[i] = ` title like '%${elem}%' `)
  var where = ` where ${kws.join(" and ")} `
  var sql = `SELECT *,(
    select md from xz_laptop_pic
    where laptop_id=lid
    limit 1
  ) as md
  FROM xz_laptop `;
  sql += where;//查全部，不分页
  //var pno=req.query.pno;
  //sql+=` limit ${pno*9},9 `;//不再用sql的limit截取
  pool.query(sql, [], (err, result) => {
    if (err) console.log(err);
    data = {};//新建结果对象
    data.pno = req.query.pno;//在结果对象中添加pno属性
    //用查询结果的总数/9,上取整，获得总页数，放入结果data中
    data.pageCount = Math.ceil(result.length / 9)
    //仅截取查询结果中的pno*9还是的9条记录，放入data中
    data.products = result.slice(data.pno * 9, data.pno * 9 + 9)
    res.send(data);
  })
  //模糊查询的测试: 
  //http://localhost:3000/products/?kw=i7 128g&pno=0,1
})
//首页商品
//index
// router.get("/index", (req, res) => {
//   var sql = `SELECT * FROM good_table
//   where id!=0
//   order by id `;
//   pool.query(sql, [], (err, result) => {
//     if (err)
//       console.log(err);
//     res.send(result);
//   })//访问http://localhost:3000/index.html
// })  //会看到花括号！
// 首页商品分页
router.get('/index', (req, res) => {
  //4.1获取查询字符串传递的数据
  var obj = req.query;
  //4.2验证是否为空
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 20;
  //4.3计算开始查询的值
  var start = (obj.pno - 1) * obj.count;
  //4.4将每页的数据量强制转为整型
  var size = parseInt(obj.count);
  //4.5执行SQL命令
  pool.query('SELECT * FROM good_table limit ?,?', [start, size], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    res.send({ code: 200, msg: '查询成功', data: result });
  });
});
//修改商品资料(post /编号)
router.post('/updatepro/:id', (req, res) => {
  //3.1获取传递的数据
  var obj1 = req.params;//路由传参
  var obj2 = req.body;//body传递
  console.log(obj1, obj2);
  //3.2验证数据是否为空
  var i = 400;
  for (var k in obj2) {
    i++;
    if (!obj2[k]) {
      res.send({ code: i, msg: k + '不能为空' });
      return;
    }
  }
  //3.3执行SQL命令，修改数据
  pool.query('update good_table set ? where id=?', [obj2, obj1.id], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    console.log(result);
    //通过result下的affectedRows判断是否成功，如果是0表示失败
    if (result.affectedRows === 0) {
      res.send({ code: 201, msg: '修改失败' });
    } else {
      res.send({ code: 200, msg: '修改成功' });
    }
  });
});

//添加商品
router.post('/addpro', (req, res) => {
  //1.1获取post请求的数据
  var obj = req.body;
  //1.2验证各项数据是否为空
  var i = 400;
  for (var k in obj) {
    i++;
    if (!obj[k]) {
      res.send({ code: i, msg: k + '不能为空' });
      return;
    }
  }
  //1.3执行SQL命令，将数据插入到数据表
  pool.query('insert into good_table set ?', [obj], (err, result) => {
    if (err) {
      console.log(err);
      res.send({ code: 500, msg: '服务器端错误' });
      return;
    }
    res.send({ code: 200, msg: '添加成功' });
  });
});
// 获取热门回收商品
router.get("/popular", (req, res) => {
  var sql = `SELECT * FROM popular_table
  where id!=0
  order by id `;
  pool.query(sql, [], (err, result) => {
    if (err)
      console.log(err);
    res.send(result);
  })//访问http://localhost:3000/popular.html
})

module.exports = router